package com.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class PostOrder {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) return result;

        TreeNode left = root.left;
        TreeNode right = root.right;

        result.addAll(postorderTraversal(left));
        result.addAll(postorderTraversal(right));
        result.add(root.val);

        return result;
    }

    public List<Integer> postorderTraversal2(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) return result;

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode node = stack.peek();
            if (node.left == null && node.right == null){
                result.add(stack.pop().val);
            }
            if (node.right != null){
                stack.push(node.right);
                node.right = null;
            }
            if (node.left != null){
                stack.push(node.left);
                node.left = null;
            }
        }
        return result;
    }
}
